package com.ruoyi.web.controller.system;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDeptEventType;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.module.estate.EstateUser;
import com.ruoyi.system.domain.module.estate.EstateUserInfo;
import com.ruoyi.system.domain.module.estate.EstateUserInfoList;
import com.ruoyi.system.service.module.estate.IEstateUserService;
import com.ruoyi.system.service.system.ISysDeptEventTypeService;
import com.ruoyi.system.service.system.ISysDeptService;
import com.ruoyi.web.controller.common.BaseController;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 部门信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController {
    @Autowired
    private ISysDeptService deptService;
	@Autowired
	private ISysDeptEventTypeService deptEventTypeService;
	@Autowired
	private ISysDeptEventTypeService sysDeptEventTypeService;
	@Autowired
	private IEstateUserService estateUserService;
	@Value("${ruoyi.imgUrl}")
	private String imgUrl;

	/**
	 * 获取部门列表
	 */
	@PreAuthorize("@ss.hasPermi('system:dept:list')")
	@GetMapping("/deptList")
	public AjaxResult dept(SysDept dept) {
		SysUser sysUser = getUser();
		if (sysUser.getUserType() < 2) {
			if (dept.getPropertyId() == null) {
				dept.setPropertyId(0);
			}
			if (dept.getEstateId() == null) {
				dept.setEstateId(0);
			}
		} else if (sysUser.getUserType() == 2) {
			dept.setPropertyId(sysUser.getPropertyId());
		} else if (sysUser.getUserType() == 3) {
			dept.setEstateId(sysUser.getEstateId());
		}
		List<SysDept> depts = deptService.selectDeptList(dept);
		return AjaxResult.success(depts);
	}

    /**
     * 获取部门列表
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public EstateUserInfoList list(SysDept dept) {
		EstateUserInfoList list = new EstateUserInfoList();
		List<EstateUserInfo> infos = new ArrayList<>();
		SysUser sysUser = getUser();
		if(sysUser.getUserType() < 2 ){
			if(dept.getPropertyId() == null){
				dept.setPropertyId(0);
			}
			if(dept.getEstateId() == null){
				dept.setEstateId(0);
			}
		} else if(sysUser.getUserType() == 2){
			dept.setPropertyId(sysUser.getPropertyId());
		} else if(sysUser.getUserType() == 3){
			dept.setEstateId(sysUser.getEstateId());
		} else {}
        List<SysDept> depts = deptService.selectDeptList(dept);

		//查询项目经理
		QueryWrapper<EstateUser> qw1 = new QueryWrapper<>();
		if (dept.getEstateId()!=null){
			qw1.eq("estate_id",dept.getEstateId());
		}
		List<EstateUser> leaderUser = estateUserService.list(qw1);
		int t = 0;
		for (EstateUser user : leaderUser){
			if (user.getIsManager()==2){
				EstateUserInfo info = new EstateUserInfo();
				if (user.getImgUrl()!=null){
					info.setImgUrl(imgUrl+user.getImgUrl());
				}
				if (user.getNickName()!=null){
					info.setNickName(user.getNickName());
				}
				info.setDeptName("项目经理");
				list.setLeaderInfo(info);
				t = 1;
			}
		}if (t == 0){
			EstateUserInfo info = new EstateUserInfo();
			info.setDeptName("项目经理");
			info.setNickName("未设置项目经理");
			info.setImgUrl("https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132");
			list.setLeaderInfo(info);
		}

		//查寻各部门主管
		if (depts!=null){
			for (SysDept dept0 :depts){
				if (dept0!=null){
					QueryWrapper<EstateUser> qw = new QueryWrapper<>();
					if (dept0.getEstateId()!=null){
						qw.eq("estate_id",dept0.getEstateId());
					}
					if (dept0.getDeptId()!=null){
						qw.eq("dept_id",dept0.getDeptId());
					}
					List<EstateUser> users = estateUserService.list(qw);
					if (users.size()>0){
						int p = 0;
						for (EstateUser user : users){
							if (user.getIsManager()==1){
								EstateUserInfo info = new EstateUserInfo();
								if (user.getImgUrl()!=null){
									info.setImgUrl(imgUrl+user.getImgUrl());
								}
								if (user.getNickName()!=null){
									info.setNickName(user.getNickName());
								}
								if (user.getDeptId()!=null){
									info.setDeptId(Math.toIntExact(user.getDeptId()));
								}
								if (dept0.getDeptName()!=null){
									info.setDeptName(dept0.getDeptName()+"主管");
								}
								infos.add(info);
								p=1;
							}
						}if (p == 0){
							EstateUserInfo info = new EstateUserInfo();
							if (dept0.getDeptName()!=null){
								info.setDeptName(dept0.getDeptName()+"主管");
							}
							if (dept0.getDeptId()!=null){
								info.setDeptId(Math.toIntExact(dept0.getDeptId()));
							}
							info.setNickName("未设置主管");
							info.setImgUrl("https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132");
							infos.add(info);
						}
						list.setStaffInfo(infos);
					}
				}
			}
		}

        return list;
    }

	@PreAuthorize("@ss.hasPermi('system:dept:list')")
	@GetMapping("/lists")
	public AjaxResult lists(SysDept dept) {
		SysUser sysUser = getUser();
		if(sysUser.getUserType() < 2){
//			dept.setPropertyId(0);
//			dept.setEstateId(0);
			if(dept.getPropertyId() == null){
				dept.setPropertyId(0);
			}
			if(dept.getEstateId() == null){
				dept.setEstateId(0);
			}
		} else if(sysUser.getUserType() == 2){
			dept.setPropertyId(sysUser.getPropertyId());
		} else if(sysUser.getUserType() == 3){
			dept.setEstateId(sysUser.getEstateId());
		} else {}
		List<SysDept> depts = deptService.selectDeptList(dept);
		return AjaxResult.success(depts);
	}

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
		SysDept dept = new SysDept();
		SysUser sysUser = getUser();
		if(sysUser.getUserType() < 2){
			dept.setPropertyId(0);
			dept.setEstateId(0);
		} else if(sysUser.getUserType() == 2){
			dept.setPropertyId(sysUser.getPropertyId());
		} else if(sysUser.getUserType() == 3){
			dept.setEstateId(sysUser.getEstateId());
		}
        List<SysDept> depts = deptService.selectDeptList(dept);
        Iterator<SysDept> it = depts.iterator();
        while (it.hasNext()) {
            SysDept d = it.next();
            if (d.getDeptId().intValue() == deptId
                    || ArrayUtils.contains(StrUtil.splitToArray(d.getAncestors(), ","), String.valueOf(deptId))) {
                it.remove();
            }
        }
        return AjaxResult.success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Integer deptId) {
		SysDept sysDept = deptService.selectDeptById(deptId);
		if(sysDept != null){
			List<Integer> eventTypeIds = new ArrayList<>();
			//小区内的部门
			if(sysDept.getEstateId() != null){
				QueryWrapper<SysDeptEventType> qw = new QueryWrapper<>();
				qw.eq("dept_id", deptId);
				List<SysDeptEventType> eventTypes = deptEventTypeService.list(qw);
				if(CollUtil.isNotEmpty(eventTypes)){
					for (SysDeptEventType eventType : eventTypes){
						eventTypeIds.add(eventType.getEventType());
					}
				}
				sysDept.setEventTypeIds(eventTypeIds);
			}
		}
        return AjaxResult.success(sysDept);
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysDept dept) {
		SysUser sysUser = getUser();
		if(sysUser.getUserType() < 2){
			if(dept.getPropertyId() == null){
				dept.setPropertyId(0);
			}
			if(dept.getEstateId() == null){
				dept.setEstateId(0);
			}
		} else if(sysUser.getUserType() == 2){
			dept.setPropertyId(sysUser.getPropertyId());
		} else if(sysUser.getUserType() == 3){
			dept.setEstateId(sysUser.getEstateId());
		}
		List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public AjaxResult roleDeptTreeselect(@PathVariable("roleId") Integer roleId) {
		SysDept dept = new SysDept();
		SysUser sysUser = getUser();
		if(sysUser.getUserType() < 2){
			if(dept.getPropertyId() == null){
				dept.setPropertyId(0);
			}
			if(dept.getEstateId() == null){
				dept.setEstateId(0);
			}
		} else if(sysUser.getUserType() == 2){
			dept.setPropertyId(sysUser.getPropertyId());
		} else if(sysUser.getUserType() == 3){
			dept.setEstateId(sysUser.getEstateId());
		}

        List<SysDept> depts = deptService.selectDeptList(dept);
		Map<String,Object> ajax = new HashMap<>();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.buildDeptTreeSelect(depts));
        return AjaxResult.success(ajax);
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept) {
//        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
//            return AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
//        }
        dept.setCreateBy(SecurityUtils.getUsername());

		SysUser sysUser = getUser();
		if(sysUser.getUserType() < 2){
			if(dept.getPropertyId() == null){
				dept.setPropertyId(0);
			}
			if(dept.getEstateId() == null){
				dept.setEstateId(0);
			}
		} else if(sysUser.getUserType() == 2){
			dept.setPropertyId(sysUser.getPropertyId());
		} else if(sysUser.getUserType() == 3){
			dept.setPropertyId(sysUser.getPropertyId());
			dept.setEstateId(sysUser.getEstateId());
		}else{
			dept.setPropertyId(0);
			dept.setEstateId(0);
		}
		if (dept.getEventTypeIds()!=null){
			for (Integer eventType : dept.getEventTypeIds()){
				SysDeptEventType sys = new SysDeptEventType();
				sys.setId(null);
				sys.setDeptId(dept.getDeptId());
				sys.setEventType(eventType);
				sysDeptEventTypeService.save(sys);
			}
		}
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept) {
//        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
//            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
//        } else
		if (dept.getParentId().equals(dept.getDeptId())) {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StrUtil.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0) {
            return AjaxResult.error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(SecurityUtils.getUsername());
		QueryWrapper<SysDeptEventType> eventType1 = new QueryWrapper<>();
		eventType1.eq("dept_id",dept.getDeptId());
		List<SysDeptEventType> eventTypes = sysDeptEventTypeService.list(eventType1);
		if (eventTypes.size()>0){
			for (SysDeptEventType type:eventTypes){
				sysDeptEventTypeService.removeById(type.getId());
			}
		}
		SysUser sysUser = getUser();
		if(sysUser.getUserType() < 2){
			if(dept.getPropertyId() == null){
				dept.setPropertyId(0);
			}
			if(dept.getEstateId() == null){
				dept.setEstateId(0);
			}
		} else if(sysUser.getUserType() == 2){
			dept.setPropertyId(sysUser.getPropertyId());
		} else if(sysUser.getUserType() == 3){
			dept.setEstateId(sysUser.getEstateId());
		}else{
			dept.setPropertyId(0);
			dept.setEstateId(0);
		}
		if (dept.getEventTypeIds()!=null){
			for (Integer eventType : dept.getEventTypeIds()){
				SysDeptEventType sys = new SysDeptEventType();
				sys.setId(null);
				sys.setDeptId(dept.getDeptId());
				sys.setEventType(eventType);
				sysDeptEventTypeService.save(sys);
			}
		}
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Integer deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return AjaxResult.error("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return AjaxResult.error("部门存在用户,不允许删除");
        }
		QueryWrapper<SysDeptEventType> eventType1 = new QueryWrapper<>();
		eventType1.eq("dept_id",deptId);
		List<SysDeptEventType> eventTypes = sysDeptEventTypeService.list(eventType1);
		if (eventTypes.size()>0){
			for (SysDeptEventType type:eventTypes){
				sysDeptEventTypeService.removeById(type.getId());
			}
		}
        return toAjax(deptService.deleteDeptById(deptId));
    }
}
